"""
Initial data creation script for the application.
Run this to create a default superuser.
"""

import asyncio
import sys
from pathlib import Path

# Add the project root to the path
sys.path.append(str(Path(__file__).parent.parent))

from app.core.database import AsyncSessionLocal
from app.crud.user import user as user_crud
from app.schemas.user import UserCreate
from app.models.user import UserType, VerificationStatus
from app.core.logging_config import get_logger

logger = get_logger(__name__)


async def create_initial_superuser():
    """Create initial superuser if it doesn't exist"""

    async with AsyncSessionLocal() as db:
        try:
            # Check if any superuser exists
            users = await user_crud.get_multi(db, limit=10)
            existing_superuser = next((u for u in users if user_crud.is_superuser(u)), None)

            if existing_superuser:
                logger.info(
                    "Superuser already exists",
                )
                return

            # Create superuser
            superuser_data = UserCreate(
                phone="19999999990",
                email="admin@example.com",
                username="admin",
                password="Admin123!",
                is_superuser=True,
                is_active=True,
                user_type=UserType.ADMIN,
                verification_status=VerificationStatus.APPROVED,
                full_name="系统管理员",
            )

            superuser = await user_crud.create(db, obj_in=superuser_data)
            await db.commit()

            logger.info("Superuser created successfully!")
            logger.info(f"Phone: {superuser.phone}")
            logger.info(f"Email: {superuser.email}")
            logger.info(f"Username: {superuser.username}")
            logger.info("Password: Admin123!")
            logger.info(f"ID: {superuser.id}")
            logger.warning("Please change the default password after first login!")
            
        except Exception as e:
            logger.error(f"Error creating superuser: {e}")
            await db.rollback()
            raise


async def main():
    """Main function to run initial data creation"""
    logger.info("Creating initial data...")
    await create_initial_superuser()
    logger.info("Initial data creation completed!")


if __name__ == "__main__":
    asyncio.run(main())
